package mblog.web.interceptor;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import mblog.core.persist.dao.UserDao;
import mblog.core.utils.BeanMapUtils;
import mtons.modules.lang.Const;
import mtons.modules.pojos.UserProfile;

import org.broadleafcommerce.profile.core.service.CustomerUserDetails;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.faxsun.core.persist.entity.UserPO;
import com.faxsun.core.readonly.dao.CustomerDao;
import com.faxsun.core.readonly.entity.CustomerRO;
import com.faxsun.web.controller.SessionConstants;

/**
 * 登陆状态拦截器，用于检查是否在电商或者资讯中已登陆，若在电商中已登陆，资讯中未登陆，则设置资讯profile。若用户在资讯中不存在，则从电商读取用户信息，
 * 并存入本地数据库
 * 
 * @author songdragon 2015年5月7日
 *
 */
@Component
public class SessionLoginInterceptor extends HandlerInterceptorAdapter {

	private static final Logger log=LoggerFactory.getLogger(SessionLoginInterceptor.class);
	
	@Autowired
	UserDao userDao;

	@Autowired
	CustomerDao customerDao;

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		HttpSession session = request.getSession();
		UserProfile up = (UserProfile) session.getAttribute(Const.KEY_LOGIN);
		SecurityContextImpl o = (SecurityContextImpl) session
				.getAttribute(SessionConstants.SPRING_SECURITY_CONTEXT);
		Long sessionCustomerId = (Long) session
				.getAttribute("_blc_overrideCustomerId");
		log.debug("sessionCustomerId="+sessionCustomerId);
		// FIXME: add url filters
		if (up == null
				&& o != null
				&& o.getAuthentication().getPrincipal() instanceof CustomerUserDetails) {
			CustomerUserDetails details = (CustomerUserDetails) o
					.getAuthentication().getPrincipal();
			// 资讯未登陆, 电商已登陆
			Long customerId = details.getId();
			loginViaSession(customerId, session);

		} else if (up==null && sessionCustomerId != null) {
			log.info("wechat login");
			// 微信中或第三方登录
			loginViaSession(sessionCustomerId, session);

		}
		return true;
	}

	private void loginViaSession(Long id, HttpSession session) {
		UserPO userPO = userDao.getByUserId(id);

		if (userPO == null) {
			saveUserDetail(userPO, id);
		}

		setSessionProfile(userPO, session);
	}

	private void saveUserDetail(UserPO userPO, Long customerId) {
		CustomerRO customer = customerDao.findById(customerId);
		// 资讯无个人信息，则创建保存
		userPO = new UserPO();
		userPO.setUsername(customer.getEmailAddress());
		userPO.setCreated(new Date(System.currentTimeMillis()));
		userPO.setName(customer.getName());
		userPO.setEmail(customer.getEmailAddress());
		userPO.setUserId(customerId);
		userPO.setStatus(0);
		userPO.setRoleLevel(0);
		userDao.save(userPO);
	}

	private void setSessionProfile(UserPO userPO, HttpSession session) {
		if (userPO == null){
			return;
		}
		
		// 资讯有个人信息，则转为userProfile，置Session
		UserProfile up = BeanMapUtils.copyPassport(userPO);
		log.debug("set profile "+up.getId()+" "+up.getName());
		session.setAttribute(Const.KEY_LOGIN, up);
	}
}
